<template>
  <div class="app-container">
    <el-form
      ref="dataForm"
      v-loading="listLoading"
      :rules="rules"
      :model="postForm"
      label-position="right"
      label-width="100px"
      style="width: 800px; margin-left:50px;"
    >
      <el-form-item  label="新闻标题" prop="xwbt">
        <el-input maxlength="20" v-model="postForm.xwbt" clearable placeholder="请输入新闻标题" />
      </el-form-item>

      <el-form-item label="新闻正文" prop="xwnr">

        <div class="login-container">
          <!-- If you need to manually control the data synchronization, you can monitor the code change event like this（如果你需要手动控制数据流，就需要像这样手动监听changed事件） -->
          <!-- <input id="quill-img" class="quill-img" type="file" @click="fileChange($event)">-->
          <quill-editor
            v-model="postForm.xwnr"
            ref="myQuillEditor"
            :options="editorOption"
            @blur="onEditorBlur($event)"
            @focus="onEditorFocus($event)"
            @change="onEditorChange($event)"
          />
        </div>
      </el-form-item>
      <el-upload
        ref="upload"
        name="upfile"
        :max-size="2048"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :on-change="handleChange"
        :on-error="handleError"
        :auto-upload="false"
        :file-list="files"
        :action="uploadAction"
        :show-upload-list="false"
        :show-file-list="false"
        class="upload-demo"
      >
        <el-button style="display: none" id="quill-img" slot="trigger" v-model="postForm.xzdz" size="small" type="file">上传图片</el-button>

      </el-upload>
      <el-form-item>
        <el-button @click="$router.back()">返回</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { saveXwgg, updateXwgg, getXwgg, uploadImg } from '@/api/portal/xwgg'
import { getUserId } from '@/utils/auth'
import { uploadFile } from "@/utils/fileCommon";

const defaultForm = {
  id: null,
  xwbt: null,
  xwnr: null
}
const toolbarOptions = [
  ['blob', 'italic', 'underline', 'strike'],
  [{ size: ['small', false, 'large', 'huge'] }],
  [{ font: [] }],
  [{ color: [] }],
  [{ align: [] }],
  ['link', 'image']
]

export default {
  name: 'XwggDetail',
  filters: {
    fbztFilter(status) {
      const statusMap = {
        0: '未发布',
        1: '已发布'
      }
      return statusMap[status]
    },
    fbztStyleFilter(status) {
      const statusMap = {
        0: 'info',
        1: 'success'
      }
      return statusMap[status]
    }
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      uploadAction: '',
      listLoading: true,
      search: '',
      files: [],
      postForm: Object.assign({}, defaultForm),
      rules: {
        xwbt: [
          { required: true, message: '新闻标题不能为空', trigger: 'change' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'change' }
        ]
      },
      content: '',
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions,
            handlers: {
              image: function(value) {
                if (value) {
                  document.getElementById('quill-img').click()
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      }
    }
  },
  computed: {
    displayTime: {
      // set and get is useful when the data
      // returned by the back end api is different from the front end
      // back end return => "2013-06-25 06:59:25"
      // front end need timestamp => 1372114765000
      get() {
        return (+new Date(this.postForm.display_time))
      },
      set(val) {
        this.postForm.display_time = new Date(val)
      }
    }
  },
  created() {
    this.fbptUrl = this.Const.IMAGE_URL
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    } else {
      this.listLoading = false
    }
  },
  methods: {
    fetchData(id) {
      getXwgg({ id: id }).then(response => {
        this.postForm = Object.assign(this.postForm, response.data)
        this.listLoading = false
      })
    },
    handleRemove() {

    },
    handleSuccess(res, file) {

    },
    handleError(res) {
      this.messageUtil.show('error', '文件上传失败')
    },
    handleChange(file, fileList) {
      const inputFile = document.querySelector('input[type=file]').files[0]
      if (!(inputFile.type === 'image/png' || inputFile.type === 'image/jpg' || inputFile.type === 'image/jpeg')) {
        this.$message({
          type: 'error',
          message: '请上传格式为jpg,jpeg,png的图片'
        })
        return
      }
      const size = file.size
      if (size > this.Const.MAX_FILE_LENGTH) {
        this.$message({
          type: 'error',
          message: '图片大小不能超过10M'
        })
        return
      }

      const reader = new FileReader()
      reader.readAsDataURL(inputFile)
      reader.onload = () => {
        this.search = reader.result
        this.uploadFile(inputFile)
      }
    },
    uploadFile(file) {
      const fileContent = this.search
      const fileName = file.name
      const fileLength = file.size
      const fileType = this.Const.FILE_TYPE
      uploadFile({ fileContent: fileContent, fileName: fileName, fileLength: fileLength, fileType: fileType }).then(response => {
        this.quillImageSuccess(response.data.url)
      })
    },
    quillImageSuccess(value) {
      const quill = this.$refs.myQuillEditor.quill
      const length = quill.getSelection().index
      quill.insertEmbed(length, 'image', value)
      quill.setSelection(length + 1)
    },
    beforeUpload(file) {

    },
    onEditorBlur(editor) {

    },
    onEditorFocus(editor) {

    },
    onEditorChange(event) {
      event.quill.deleteText(1500, 4)
    },
    submitForm() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.listLoading = true
          if (this.isEdit) {
            this.postForm.modifiedBy = getUserId()
            updateXwgg(this.postForm).then(response => {
              const returnCode = response && response.returnCode
              const type = this.Const.OK === returnCode ? 'success' : 'error'
              this.$message({
                type: type,
                message: '更新成功'
              })
              if (this.Const.OK === returnCode) {
                this.$router.back()
              }
              this.listLoading = false
            }).catch(() => {
              this.$message({
                type: 'error',
                message: '更新失败'
              })
              this.listLoading = false
            })
          } else {
            this.postForm.createdBy = getUserId()
            saveXwgg(this.postForm).then(response => {
              const returnCode = response && response.returnCode
              if (this.Const.OK === returnCode) {
                this.$message({
                  type: 'success',
                  message: '保存成功'
                })
                this.listLoading = false
                this.$router.back()
              } else {
                this.$message({
                  type: 'error',
                  message: response && response.msg || '保存失败'
                })
                this.listLoading = false
              }
            }).catch(() => {
              this.$message({
                type: 'error',
                message: '保存失败'
              })
              this.listLoading = false
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped>
  .login-container{
    width: 700px;
    height: 650px;
  }
  .quill-editor{
    height: 550px;
  }
</style>
